package net.hust.dao;

import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import net.hust.bean.Song;
import net.hust.service.SongQryHelper;

public class SongDAOImp extends HibernateDaoSupport implements SongDAO{

	public void addSong(Song song) {
		this.getHibernateTemplate().save(song);

	}

	public void deleteSong(Song song) {
		Song songTemp = (Song)this.getHibernateTemplate().load(Song.class, song.getId());
		this.getHibernateTemplate().delete(songTemp);

	}

	public Integer getCountSongs(SongQryHelper helper) {
		DetachedCriteria criteria=this.buildCriteria(helper);
		criteria.setProjection(Projections.rowCount());
		return (Integer)this.getHibernateTemplate().findByCriteria(criteria).get(0);
	}

	public Song getSongById(Integer id) {
		return (Song)this.getHibernateTemplate().get(Song.class, id);
	}

	public List<Song> loadAll(int startIndex, int fetchSize,
			SongQryHelper helper) {
		DetachedCriteria criteria=this.buildCriteria(helper);
		List<Song> Songs = this.getHibernateTemplate().findByCriteria(criteria, startIndex - 1, fetchSize);
		return Songs;
	}

	public void updateSong(Song song) {
		this.getHibernateTemplate().update(song);

	}
	
	private DetachedCriteria buildCriteria(SongQryHelper helper)
	{
		
		DetachedCriteria criteria=DetachedCriteria.forClass(Song.class);
		
		if (StringUtils.isNotEmpty(helper.getName()))
			criteria.add(Restrictions.like("name", helper.getName().trim(), MatchMode.ANYWHERE));

		if (StringUtils.isNotEmpty(helper.getSinger()))
			criteria.add(Restrictions.like("singer", helper.getSinger().trim(), MatchMode.ANYWHERE));
		
		if (StringUtils.isNotEmpty(helper.getStyle()))
			criteria.add(Restrictions.like("style", helper.getStyle().trim(), MatchMode.ANYWHERE));
		
		if (helper.getSortHelper() != null){
			if(helper.getSortHelper().getSortedType().equals("desc"))
			   criteria.addOrder(Property.forName(helper.getSortHelper().getColName()).desc());
			else
			   criteria.addOrder(Property.forName(helper.getSortHelper().getColName()).asc());	
		}
		
		return criteria;
	}


}
